import urllib2
import datetime
from google.appengine.ext import db
from models import Quote


# Pobranie notowania indeksow WIG20
handler = urllib2.urlopen("http://bossa.pl/pub/ciagle/mstock/sesjacgl/sesjacgl.prn")
csv_content = handler.read()
cgl_lines = csv_content.split('\n')
if len(cgl_lines) > 0:
    first_line_parts = cgl_lines[0].strip().split(',')
    if len(first_line_parts) != 7:
        raise Exception("Brak danych na serwerze danych")

# Pobranie notowan kontraktow i opcji
handler = urllib2.urlopen("http://bossa.pl/pub/futures/mstock/sesjafut/sesjafut.prn")
csv_content = handler.read()
fut_lines = csv_content.split('\n')
if len(fut_lines) > 0:
    first_line_parts = fut_lines[0].strip().split(',')
    if len(first_line_parts) != 8:
        raise Exception('Brak danych na serwerze danych')

# Deaktywowanie wszystkich aktywnych notowan z bazy
query = Quote.all().filter("is_last =", True)

quotes_need_update = []
for q in query:
    q.is_last = False
    quotes_need_update.append(q)

if len(quotes_need_update) > 0:
    db.put(quotes_need_update)

def add_quote_from_csv_line(parts, sym_type):
    symbol = parts[0]
    date = datetime.date(int(parts[1][0:4]), int(parts[1][4:6]), int(parts[1][6:8]))
    
    open_val = float(parts[2])
    high_val = float(parts[3])
    low_val = float(parts[4])
    close_val = float(parts[5])
    
    if '.' in parts[6]:
        volume = int(float(parts[6]))
    else:
        volume = int(parts[6])

    if len(parts) == 8:
        lop = int(parts[7])
    else:
        lop = 0 
    
    # Akutalizacja lub utworzenie encji
    q = Quote.all().filter("name =", symbol).filter("type =", sym_type).filter("date =", date).get()
    if q is None:
        q = Quote(name=symbol, type=sym_type, date=date)
        
    q.open = open_val
    q.high = high_val
    q.low = low_val
    q.close = close_val
    q.volume = volume
    q.lop = lop
    q.is_last = True
    
    q.put()

# Wczytywanie nowych notowac indeksu
for line in cgl_lines:
    parts = line.strip().split(',')
    if len(parts) != 7:
        continue

    if parts[0] == 'WIG20':
        sym_type = 'I'
    else:
        continue

    add_quote_from_csv_line(parts, sym_type)

# Wczytanie nowych aktywnych notowan futures
for line in fut_lines:
    parts = line.strip().split(',')
    if len(parts) < 8:
        continue
    
    if parts[0].startswith('OW20'):
        sym_type = 'O'
    elif parts[0] == 'FW20':
        sym_type = 'F'
    else:
        continue

    add_quote_from_csv_line(parts, sym_type)

print "GOTOWE !"
